<script setup>
import {reactive, ref,onMounted} from 'vue'
import {get,post}  from '@/myaxios'
import axios  from 'axios'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import router from '@/router'

//table列表数据
const tableData = reactive({tableList:[],
                            pageInfo:{
                              page:2,
                              pageSize:5,
                              total:25
                            }
})
//查询表单对象
const queryForm = reactive({
  username:'',
  isvalid:''
})

//查询表单组件
const queryFormRef = ref();

//重置查询表单
const queryReset = ()=>{
  queryFormRef.value.resetFields();
  queryData({})
}

//点击查询按钮
const querySubmit = ()=>{
  queryData(queryForm)
}

//页码切换
const handleCurrentChange = (page)=>{
  tableData.pageInfo.page = page;
  //json合并对象
  let params = {...tableData.pageInfo,...queryForm}

  queryData(params)
}
//pageSize切换
const handleSizeChange = (pageSize) =>{
  tableData.pageInfo.page = 1;
  tableData.pageInfo.pageSize = pageSize;
  //json合并对象
  let params = {...tableData.pageInfo,...queryForm}
  queryData(params)

}

//查询公共函数
const queryData = async(params)=>{
  let resp = await get("/users/listUser",params)
  console.log(resp.data);
  //根据响应码 在页面做不同的处理
  if(resp.data.code == 2000){
    tableData.tableList = resp.data.returnData;
    tableData.pageInfo = resp.data.pageInfo;
  }else if(resp.data.code == 2001){
    tableData.tableList = [];
    tableData.pageInfo = {page:1,total:0,pageSize:5};
  }  
  
}

//密码数据脱敏
const changePwd = (currentPwd)=>{
  let startStr = currentPwd.substr(0,1)
  let lastStr = currentPwd.substr(currentPwd.length-1,1)
  return startStr+"****"+lastStr
}



/**添加功能 */
//控制抽屉显示隐藏
const addDrawerVisable = ref(false)

//添加表单对象
const addForm = reactive({
  username:'',
  headImg:''
})

//添加表单组件
const addFormRef = ref()
//打开抽屉
const openAdd = ()=>{
  addDrawerVisable.value = true
  if(addFormRef.value!=undefined){
    addFormRef.value.resetFields()
  }
}

//添加抽屉保存数据
const addSubmit = ()=>{
  //关闭抽屉
  addDrawerVisable.value = false
  //调用接口处理数据  
  dataOperation("/users/addUser",addForm)


}

/**修改功能 */
//修改对话框显示隐藏
const updateDrawerVisable = ref(false)
//修改表单数据
const editForm = reactive({editData:{
  uid:'',
  username:'',
  password:'',
  isvalid:'',
  headImg:''
}})
//修改开框
const openUpdate = (rowData)=>{
  //开框
  updateDrawerVisable.value = true
  //vue中响应式对象一旦形成 引用到这个响应式对象的位置 有一个位置发生改变 其他都会跟着变
  //json对象复制 深克隆 JSON.parse(JSON.stringify(rowData))
  // console.log(rowData);
  // console.log(JSON.parse(JSON.stringify(rowData)) );
  editForm.editData = JSON.parse(JSON.stringify(rowData)) 

}
//修改提交
const updateSubmit = ()=>{
  //关框
  updateDrawerVisable.value = false
  //调用接口处理数据  
  dataOperation("/users/updateUser",editForm.editData)


}

/**删除功能 */
const tableRef = ref();

const openDelete = ()=>{
  let currentRow = tableRef.value.getSelectionRows();
 
  if(currentRow.length==0){
    ElMessage.warning("请选择数据....")
  }else{
    let listUid = [];
    currentRow.forEach(userData=>{
      listUid.push(userData.uid) 
    })
    let listUidStr = listUid.join();
    console.log(listUidStr);
    //弹出对话框 询问是否删除
    ElMessageBox.confirm(
            `是否删除编号为 [${listUidStr}] 的数据?`,
            '注意',
            {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
            })
    .then(()=>{
        //调用接口处理数据  
        dataOperation("/users/deleteUser",{'listUid':listUidStr})
    })
    .catch(()=>{})        


  }
  
}



/**授权功能 */

//授权框显示隐藏
const authVisible = ref(false)
//授权列表框
const authData = reactive({menuList:[]})

const treeRef = ref()
//
const defaultProps = {
  children: 'subMenu',
  label: 'menuname',
}

//授权表单对象
const authForm = reactive({
  uid:'',
  listMid:''
})


//授权开框
const openAuth = async (rowData)=>{
  authVisible.value = true
  //修改的编号显示到修改权限框内
  authForm.uid = rowData.uid

  console.log(rowData);
  let resp = await get("/users/readyForAuth",{uid:rowData.uid});
  //展示菜单列表
  authData.menuList = resp.data.returnData.menuWithSub
  //购中选项
  treeRef.value.setCheckedKeys(resp.data.returnData.userMenuId)
}

//授权保存
const authSubmit = ()=>{
  //1 关框
  authVisible.value = false

  //2 操作数据
  let listMidArr = treeRef.value.getCheckedKeys(true)
  console.log(listMidArr);
  authForm.listMid = listMidArr.join(",")
  //把uid listMid 传给后端 保存权限
  dataOperation("/users/updateUserAuth",authForm)

}

//添加头像上传
const addUpload = async (rowFile)=>{
  //取到文件
  console.log(rowFile.file);
  //创建formdata
  let newForm = new FormData();
  //文件放入formdata
  newForm.append("myFile",rowFile.file)

  //通过axios请求发送
  let resp = await axios.post("http://localhost:8080/projectDemo/myupload",newForm)
  ElMessage.success(resp.data.msg)
  addForm.headImg = resp.data.returnData
  
}


//修改上传
const updateUpload = async(rowFile)=>{
  let myFile = rowFile.file;
  let newForm = new FormData();
  newForm.append("myFile",myFile)
  let resp = await axios.post("http://localhost:8080/projectDemo/myupload",newForm)
  ElMessage.success(resp.data.msg)
  //给修改框赋值
  editForm.editData.headImg = resp.data.returnData

}


//数据操作公共函数
const dataOperation = async (url,params)=>{
  let resp =  await post(url,params)
  //根据响应显示不同的弹窗
  if(resp.data.code == 2010){
    ElMessage.success(resp.data.msg)
  }else{
    ElMessage.error(resp.data.msg)
  }
  //刷新数据
  //json合并对象
  let queryParams = {...tableData.pageInfo,...queryForm}
  queryData(queryParams)

}


onMounted(()=>{
  queryData({})

})


</script>

<template>
  
  <!-- "headImg": "https://192.168.0.236:8080/baseProj/imgs/ea18886a-21d5-4554-80fe-c465a9c9e462.png",
            "isvalid": 1,
            "password": "abc123",
-->

<el-form ref="queryFormRef" :inline="true" :model="queryForm" class="demo-form-inline">
    <el-form-item label="用户名" prop="username">
      <el-input style="width:240px" v-model="queryForm.username" placeholder="username" />
    </el-form-item>
    <el-form-item label="用户状态" prop="isvalid">
      <el-select
        style="width:240px"
        v-model="queryForm.isvalid"
        placeholder="isvalid"
      >
        <el-option label="在职" value="1" />
        <el-option label="离职" value="0" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
      <el-button plain @click="queryReset">重置</el-button>
      <el-button type="primary" @click="openAdd">添加</el-button>
      <el-button type="primary" @click="openDelete">删除</el-button>
    </el-form-item>
  </el-form>
  <el-table ref="tableRef" :data="tableData.tableList" style="width: 100%" height="480">
    <el-table-column fixed type="selection"  width="55" />
    <el-table-column fixed prop="uid" label="编号"  />
    <el-table-column prop="username" label="名称" width="180" />
    <el-table-column  label="创建人" >
      <template #default="scope">
        {{ scope.row.createUid }}- {{ scope.row.createUsername }}
      </template>
    </el-table-column>
    <el-table-column prop="regTime" label="注册时间" width="180" />
    <el-table-column prop="loginTime" label="最后登录时间" width="180" />
    <el-table-column prop="isvalid" label="是否可用" >
      <template #default="scope">
        <el-text v-if="scope.row.isvalid == 1" type="success">在职</el-text>
        <el-text v-else type="info">离职</el-text>
      </template>
    </el-table-column>
    <el-table-column prop="password" label="密码" >
      <template #default="scope">
        {{ changePwd(scope.row.password) }} 
      </template>
    </el-table-column>
    <el-table-column prop="headImg" label="头像" >
      <template #default="scope">
        <img :src="scope.row.headImg"/>
        <!-- <img src=""/> -->
      </template>
    </el-table-column>
    <el-table-column fixed="right" width="240"  label="操作" >
      <template #default="scope">
          <el-button plain @click="openUpdate(scope.row)">修改</el-button>
          <el-button plain @click="openAuth(scope.row)">授权</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="tableData.pageInfo.page"
      v-model:page-size="tableData.pageInfo.pageSize"
      :total="tableData.pageInfo.total"
      :page-sizes="[5,10]"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      
    />

    <el-drawer
    v-model="addDrawerVisable"
    title="添加"
    direction="rtl"
    size="50%"
  >
  <el-form ref="addFormRef" :model="addForm" label-width="80" style="max-width: 600px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username" />
    </el-form-item>
    <el-form-item label="头像地址" prop="headImg">
      <!-- <el-input v-model="addForm.headImg" /> -->
      <el-upload
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="addUpload"
      >
        <img v-if="addForm.headImg" :src="addForm.headImg" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>

    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="addSubmit">保存</el-button>
    </el-form-item>
  </el-form>  
  </el-drawer>


  <el-drawer
    v-model="updateDrawerVisable"
    title="修改"
    direction="rtl"
    size="50%"
  >
  <el-form  :model="editForm.editData" label-width="80" style="max-width: 600px">
    <el-form-item label="编号" prop="uid">
      <el-input disabled v-model="editForm.editData.uid" />
    </el-form-item>
    <el-form-item label="用户名" prop="username">
      <el-input v-model="editForm.editData.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="editForm.editData.password" />
    </el-form-item>
    <el-form-item label="用户状态" prop="isvalid">
      <el-select
        style="width:100%"
        v-model="editForm.editData.isvalid"
      >
        <el-option label="在职" :value="1" />
        <el-option label="离职" :value="0" />
      </el-select>
    </el-form-item>
    <el-form-item label="头像地址" prop="headImg">
      <!-- <el-input v-model="editForm.editData.headImg" /> -->
      <el-upload
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="updateUpload"
      >
        <img v-if="editForm.editData.headImg" :src="editForm.editData.headImg" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>



    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateSubmit">保存</el-button>
    </el-form-item>
  </el-form>  
  </el-drawer>

  <el-dialog
    v-model="authVisible"
    title="授权"
    width="500"
  >
  <el-form :model="authForm" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户编号">
      <el-input disabled v-model="authForm.uid" />
    </el-form-item>
    <el-form-item label="权限列表">
      <!-- <el-input v-model="authForm.listMid" /> -->
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="authData.menuList"
        show-checkbox
        default-expand-all
        node-key="mid"
        :props="defaultProps"
      />

    </el-form-item>

  </el-form>

    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="authVisible = false">取消</el-button>
        <el-button type="primary" @click="authSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>



</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

img{
  width: 60px;
  height: 60px;
}


</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}


</style>